import { ProLayout } from '@ant-design/pro-components';
import { Link, useModel, useLocation } from '@umijs/max';
import { Outlet } from '@umijs/max';
import defaultSettings from '../../config/defaultSettings';
import { AvatarDropdown, AvatarName, Footer } from '@/components';
import { useState, useEffect } from 'react';

const BasicLayout: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const location = useLocation();
  const [menuData, setMenuData] = useState<any[]>([]);
  const [buttonData, setButtonData] = useState<any[]>([]);
  const [breadcrumb, setBreadcrumb] = useState<any[]>([]);
  const [currentPageId, setCurrentPageId] = useState<string | null>(() => {
    // 从 localStorage 恢复 currentPageId
    return localStorage.getItem('currentPageId');
  });

  // 根据路径查找对应的菜单项
  const findBreadcrumb = (menus: any[], path: string, breadcrumb: any[] = []): any[] => {
    for (const menu of menus) {
      if (menu.path === path) {
        return [...breadcrumb, menu];
      }
      if (menu.children) {
        const found = findBreadcrumb(menu.children, path, [...breadcrumb, menu]);
        if (found) return found;
      }
    }
    return [];
  };

  const findMenuByPath = (menus: any[], path: string): any => {
    const findBreadcrumb = (menus: any[], path: string, breadcrumb: any[] = []): any[] => {
      for (const menu of menus) {
        if (menu.path === path) {
          return [...breadcrumb, menu];
        }
        if (menu.children) {
          const found = findBreadcrumb(menu.children, path, [...breadcrumb, menu]);
          if (found) return found;
        }
      }
      return [];
    };
    for (const menu of menus) {
      if (menu.path === path) {
        return menu;
      }
      if (menu.children) {
        const found = findMenuByPath(menu.children, path);
        if (found) return found;
      }
    }
    return null;
  };

  // 监听路由变化，设置当前页面ID
  useEffect(() => {
    if (initialState?.menus) {
      const breadcrumb = findBreadcrumb(initialState.menus, location.pathname);
      setBreadcrumb(breadcrumb);
      const currentMenu = findMenuByPath(initialState.menus, location.pathname);
      if (currentMenu) {
        setCurrentPageId(currentMenu.id);
        // 保存 currentPageId 到 localStorage
        localStorage.setItem('currentPageId', currentMenu.id);
        console.log('Current page ID:', currentMenu.id);
      }
    }
  }, [location.pathname, initialState?.menus]);

  useEffect(() => {
    // 从 localStorage 获取菜单数据
    const cachedMenus = localStorage.getItem('menus');
    console.log('Cached menus:', cachedMenus);
    console.log('Initial state menus:', initialState?.menus);

    if (cachedMenus) {
      try {
        const parsedMenus = JSON.parse(cachedMenus);
        // 确保菜单数据是数组
        if (Array.isArray(parsedMenus) && parsedMenus.length > 0) {
          setMenuData(parsedMenus);
          console.log('Set menu data from cache:', parsedMenus);
        }
      } catch (error) {
        console.error('Error parsing cached menus:', error);
      }
    }

    // 如果有新的菜单数据，更新到 localStorage
    if (initialState?.menus && Array.isArray(initialState.menus)) {
      localStorage.setItem('menus', JSON.stringify(initialState.menus));
      setMenuData(initialState.menus);
      console.log('Set menu data from initialState:', initialState.menus);
    }

         // 提取按钮
    const extractButtons = (menus: any[], id: string | null) => {
      let buttons: any[] = [];
      console.log('开始处理菜单，菜单数量:', menus.length);
      menus.forEach(menu => {
        console.log('按钮处理，，，', menu);
        if (menu.children) {
          console.log('存在子菜单，递归处理子菜单');
          buttons = [...buttons, ...extractButtons(menu.children, id)];
        }
        console.log('menu.resourceParentId', menu.resourceParentId, 'id:', id);
        if (menu.resourceType === 'button' ) {
          console.log('找到符合条件的按钮:', menu);
          buttons.push(menu);
        }
      });
      console.log('buttons for id:', id, buttons);
      return buttons;
    };
    if (initialState?.menus && Array.isArray(initialState.menus) && currentPageId) {
      const buttons = extractButtons(initialState.menus, currentPageId);
      console.log('buttons11:', buttons);

      setButtonData(buttons);


      console.log('Set button data from initialState:', buttons);
    }
  }, [initialState?.menus, currentPageId]);

  const formatMenuData = (menus: any[]) => {
    console.log('Formatting menu data:', menus);
    if (!menus || !Array.isArray(menus)) return [];
    const filteredMenus = menus.filter(menu => menu.resourceType === 'menu' || menu.resourceType === 'page');
    console.log('Filtered menus:', filteredMenus);
    return filteredMenus.map(menu => ({
      path: menu.path,
      name: menu.resourceName,
      // icon: menu.iconPath || 'menu',
      children: menu.children ? formatMenuData(menu.children) : undefined,
      hideInMenu: menu.visible === 0,
    }));
  };

  return (
    <ProLayout
      {...defaultSettings}
      style={{
        // marginLeft:'-3%',
      }}
      title="企业服务平台"
      avatarProps={{
        src: initialState?.currentUser?.avatar,
        title: <AvatarName />,
        render: (_, avatarChildren) => {
          return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
        },
      }}
      menuDataRender={() => {
        const formattedMenus = formatMenuData(menuData);
        console.log('Rendered menu data:', formattedMenus);
        return formattedMenus;
      }}
      menuItemRender={(menuItemProps, defaultDom) => {
        if (menuItemProps.isUrl || !menuItemProps.path) {
          return defaultDom;
        }
        return <Link to={menuItemProps.path}>{defaultDom}</Link>;
      }}
      footerRender={() => <Footer />}
    >
       <Outlet context={{ buttonData }} />
    </ProLayout>
  );
};

export default BasicLayout;
